package top.superflow.flow.config.parse.center

import top.superflow.exception.RequestUnsupportedException
import top.superflow.flow.config.parse.Parser
import top.superflow.flow.config.{Config, Identifiable}
import top.superflow.log.Loggable

import scala.collection.mutable._

trait ParserCenter[C <: Config, P <: Parser[_ <: Identifiable]] extends Loggable{


  private final val parsers : Map[String , P] = Map()

  def register(configType : Class[C], parser : P ): Unit ={
    if(configType == null){
      return;
    }

    this.register(configType.getName, parser)
  }

  def register(configParserKey : String, parser : P ): Unit ={
    if(configParserKey == null){
      return;
    }

    if(parser == null){
      throw new UnsupportedOperationException("Can't register null to config type [" + configParserKey + "]")
    }

    if(parsers.contains(configParserKey)){
      throw new RequestUnsupportedException("There is already a parser for [" + configParserKey + "], it's  [" + parser.getClass.getName + "], it can't be overridden")
    }

    parsers.put(configParserKey, parser)
  }

  def getParser(configParserKey : Class[C]) : P = {
    if(configParserKey == null){
      logger.warn("There is process parser for the process config type [{}]", configParserKey )
      return null.asInstanceOf[P]
    }

    this.getParser(configParserKey.getName)
  }


  def getParser(configParserKey : String) : P = {
    if(configParserKey == null || !parsers.contains(configParserKey)){
      logger.warn("There is process parser for the process config type [{}]", configParserKey )
      return null.asInstanceOf[P]
    }

    return parsers.get(configParserKey).get
  }

  def contains(configParserKey : String): Boolean ={
    return this.parsers.contains(configParserKey)
  }
}

